<template>
  <div class="container" v-loading="loading">
    <el-divider content-position="left"><span class="title-left-color">用户基本信息</span></el-divider>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="150px" :validate-on-rule-change="false">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="商品分类1：" prop="cat_id1">
            <el-select v-model.trim="form.cat_id1" placeholder="请选择商品分类1" clearable :disabled="methodType == 'PUT'" @change="val => handleChangeCategory(val, 2)">
              <el-option v-for="item in category1List" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品分类2：" prop="cat_id2">
            <el-select v-model.trim="form.cat_id2" placeholder="请选择商品分类2" clearable @change="val => handleChangeCategory(val, 3)">
              <el-option v-for="item in category2List" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" v-if="!showLocalCategory">
        <el-col :span="6">
          <el-form-item label="本店分类1：" prop="store_cat_id1">
            <el-select v-model.trim="form.store_cat_id1" placeholder="请选择本店分类1" clearable :disabled="methodType == 'PUT'" @change="handleChangeStoreCategory">
              <el-option v-for="item in storeCategory1List" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="本店分类2：" prop="store_cat_id2">
            <el-select v-model.trim="form.store_cat_id2" placeholder="请选择本店分类2" clearable>
              <el-option v-for="item in storeCategory2List" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="手机型号：" prop="goods_name">
            <el-input v-model="form.goods_name" placeholder="请填写手机型号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="下单平台：" prop="platform">
            <el-select v-model.trim="form.platform" multiple placeholder="请选择下单平台">
              <el-option v-for="item in platformList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="租赁模式：" prop="order_rent_type_ids">
            <el-select :model-value="form.order_rent_type_ids" multiple placeholder="请选择租赁模式" @change="handleChangePlatformRentType">
              <el-option v-for="item in optionalOrderRentTypeList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品状态：" prop="is_on_sale">
            <el-select v-model.trim="form.is_on_sale" clearable placeholder="请选择商品状态">
              <el-option v-for="item in saleList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="商品成色：" prop="fineness">
            <el-select v-model.trim="form.fineness" placeholder="请选择商品成色" clearable>
              <el-option v-for="item in finenessList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="排序：" prop="sort">
            <el-input v-model.number="form.sort" clearable placeholder="请填写排序"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="基础销量：" prop="basic_sales_sum">
            <el-input v-model.number="form.basic_sales_sum" clearable placeholder="请填写基础销量"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="showMaxMinPrice">
          <el-form-item label="热销排名：" prop="hot_sell_rank">
            <el-select v-model.trim="form.hot_sell_rank" clearable placeholder="请选择热销排名">
              <el-option v-for="item in rankList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6" v-if="showShopPrice">
          <el-form-item label="批发价：" prop="shop_price">
            <el-input v-model.trim="form.shop_price" clearable placeholder="请填写批发价"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="showRetailPrice">
          <el-form-item label="零售价：" prop="retail_price">
            <el-input v-model.trim="form.retail_price" clearable placeholder="请填写零售价"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="showBuyoutPriceAndAdvancePrice || showBuyoutPriceAndDepositPrice">
          <el-form-item label="买断价：" prop="buyout_price">
            <el-input v-model.trim="form.buyout_price" clearable placeholder="请填写买断价"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="showBuyoutPriceAndDepositPrice">
          <el-form-item label="押金：" prop="deposit_price">
            <el-input v-model.trim="form.deposit_price" clearable placeholder="请填写押金"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="showBuyoutPriceAndAdvancePrice">
          <el-form-item label="首付：" prop="advance_price">
            <el-input v-model.trim="form.advance_price" clearable placeholder="请填写首付"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="showAnyMonthPrice">
          <el-form-item label="月供价：" prop="month_price">
            <el-input v-model.trim="form.month_price" clearable placeholder="请填写月供价"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="showAnyMonthPrice">
          <el-form-item label="下一年月供价：" prop="next_year_month_price">
            <el-input v-model.trim="form.next_year_month_price" clearable placeholder="请填写下一年月供价"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="showOfflineRental">
          <el-form-item label="是否补差价：" prop="is_diff_price">
            <el-select v-model.trim="form.is_diff_price" clearable placeholder="请选择是否补差价">
              <el-option v-for="item in selectWhether" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品标签：" prop="goods_tags">
            <el-select v-model.trim="form.goods_tags" multiple placeholder="请选择商品标签">
              <el-option v-for="item in goodsTagList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="商品主图：" prop="original_img">
            <UploadImageInfo :imageWidth="178" :imageHeight="178" :limit="600" suggestInfo="建议：尺寸200*200,大小600k以下" v-model:disabledbtn="disabledbtn" v-model:loading="loading" imageKey="original_img" v-model:form="form" />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="!showOfflineRental">
          <el-form-item label="轮播视频：" prop="original_video">
            <UploaVideoInfo suggestInfo="建议：上传20s以内的短视频，大小10M以下。只能上传一个视频" v-model:disabledbtn="disabledbtn" v-model:loading="loading" videoKey="original_video" v-model:form="form" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" v-show="!showOfflineRental">
        <el-col :span="24">
          <el-form-item label="商品轮播图：" prop="image">
            <UploadImageListInfo ref="uploadImageListRef" group="image" v-model:disabledbtn="disabledbtn" v-model:loading="loading" v-model:imageList="form.image" :imageNum="imageNum" suggestInfo="建议：尺寸750x750像素以上(等比例亦可)，大小1M以下" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 规格信息 -->
      <el-divider content-position="left"><span class="title-left-color">规格信息</span></el-divider>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="库存：" prop="store_count">
            <el-input v-model="form.store_count" disabled placeholder="库存"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="内存：">
            <draggable v-model="form.sku.memory_list" group="memory_list" animation="500" class="tags-info" @change="handleChangDraggable">
              <div :key="item.id" v-for="item in form.sku.memory_list">
                <el-tag closable size="large" type="primary" :disable-transitions="false" @close="handleDeleteColorValue(item.item, 'memory', 'memory_list')">
                  {{ item.item }}
                </el-tag>
              </div>
            </draggable>
            <el-input class="input-new-tag" v-if="specInfo.memory.inputVisible" ref="memoryInputRef" v-model="specInfo.memory.inputValue" @blur="handleInputConfirm('memory', 'memory_list')" @keyup.enter="handleInputConfirm('memory', 'memory_list')"> </el-input>
            <el-button v-else class="button-new-tag" @click="showInput('memory')">+ 新增</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10" v-if="!showOfflineRental">
        <el-col :span="10">
          <el-form-item label="颜色：">
            <draggable v-model="form.sku.color_list" group="color_list" animation="500" class="tags-info" @change="handleChangDraggable">
              <div class="ibDraggable" :key="item.id" v-for="item in form.sku.color_list">
                <el-tag closable size="large" type="primary" :disable-transitions="false" @close="handleDeleteColorValue(item.item, 'color', 'color_list')">
                  {{ item.item }}
                </el-tag>
              </div>
            </draggable>
            <el-input class="input-new-tag" v-if="specInfo.color.inputVisible" ref="colorInputRef" v-model="specInfo.color.inputValue" @blur="handleInputConfirm('color', 'color_list')" @keyup.enter="handleInputConfirm('color', 'color_list')"> </el-input>
            <el-button v-else class="button-new-tag" @click="showInput('color')">+ 新增</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-table :data="form.sku.spec_list" border class="table" ref="multipleTable1" :reserve-selection="true">
        <el-table-column type="index" align="center"> </el-table-column>
        <el-table-column prop="memory" label="内存" key="memory" align="center"> </el-table-column>
        <el-table-column prop="color" label="颜色" align="center" key="color" v-if="!showOfflineRental"> </el-table-column>
        <el-table-column prop="price" :label="showOfflineRental ? '指导价' : '批发价'" align="center" key="price" v-if="showShopPrice || showOfflineRental || showOldMobiloeInfo">
          <template #default="scope">
            <div class="">
              <el-input v-model.trim="scope.row.price" placeholder="请输入批发价" @change="value => handleChangeSkuPrice(value, scope.row, 'price')"></el-input>
            </div>
          </template>
        </el-table-column>
        <!-- key的作用，动态显示列的时候，就不会错乱顺序 -->
        <el-table-column prop="retail_price" :label="showOfflineRental ? '最高限价' : '零售价'" align="center" key="retail_price" v-if="showRetailPrice || showMaxMinPrice || showOfflineRental || showOldMobiloeInfo">
          <template #default="scope">
            <div class="">
              <el-input v-model.trim="scope.row.retail_price" placeholder="请输入零售价" @change="value => handleChangeSkuPrice(value, scope.row, 'retail_price')"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="regulatory_recycling_price" label="监管机回收价" align="center" key="regulatory_recycling_price" v-if="showOfflineRental">
          <template #default="scope">
            <div class="">
              <el-input v-model.trim="scope.row.regulatory_recycling_price" placeholder="请输入监管机回收价" @change="value => handleChangeSkuPrice(value, scope.row, 'regulatory_recycling_price')"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="buyout_price" label="买断价" align="center" key="buyout_price" v-if="showBuyoutPriceAndAdvancePrice || showBuyoutPriceAndDepositPrice">
          <template #default="scope">
            <div class="">
              <el-input v-model.trim="scope.row.buyout_price" placeholder="请输入买断价" @change="value => handleChangeSkuPrice(value, scope.row, 'buyout_price')"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="advance_price" label="首付" align="center" key="advance_price" v-if="showBuyoutPriceAndAdvancePrice">
          <template #default="scope">
            <div class="">
              <el-input v-model.trim="scope.row.advance_price" placeholder="请输入首付" @change="value => handleChangeSkuPrice(value, scope.row, 'advance_price')"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="deposit_price" label="押金" align="center" key="deposit_price" v-if="showBuyoutPriceAndDepositPrice">
          <template #default="scope">
            <div class="">
              <el-input v-model.trim="scope.row.deposit_price" placeholder="请输入押金" @change="value => handleChangeSkuPrice(value, scope.row, 'deposit_price')"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="subsidy_price" label="奖励" align="center" key="subsidy_price" v-if="showBuyoutPriceAndDepositPrice">
          <template #default="scope">
            <div class="">
              <el-input v-model.trim="scope.row.subsidy_price" placeholder="请输入奖励" @change="value => handleChangeSkuPrice(value, scope.row, 'subsidy_price')"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="month_price" label="月供价" align="center" key="month_price" v-if="showAnyMonthPrice || showMonthPrice">
          <template #default="scope">
            <div class="">
              <el-input v-model.trim="scope.row.month_price" placeholder="请输入月供价" @change="value => handleChangeSkuPrice(value, scope.row, 'month_price')"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="next_year_month_price" label="下一年月供价" align="center" key="next_year_month_price" v-if="showAnyMonthPrice">
          <template #default="scope">
            <div class="">
              <el-input v-model.trim="scope.row.next_year_month_price" placeholder="请输入下一年月供价" @change="value => handleChangeSkuPrice(value, scope.row, 'next_year_month_price')"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="store_count" label="库存" align="center">
          <template #default="scope">
            <div class="">
              <el-input v-model.number="scope.row.store_count" placeholder="请输入库存" @change="handleChangeStoreCount"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sku" label="sku" align="center">
          <template #default="scope">
            <div class="">
              <el-input v-model.trim="scope.row.sku" placeholder="请输入sku"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="图片(默认为主图)" align="center" width="150">
          <template #default="scope">
            <UploadImageInfo suggestInfo="" v-model:disabledbtn="disabledbtn" v-model:loading="loading" imageKey="image" v-model:form="scope.row" isCenter />
          </template>
        </el-table-column>
      </el-table>
      <el-divider content-position="left" v-if="!showOfflineRental"><span class="title-left-color">商品详情</span></el-divider>
      <el-row :gutter="10" v-if="!showOfflineRental">
        <el-col :span="24">
          <el-form-item label="商品详情：" prop="content">
            <UploadImageListInfo ref="uploadContentListRef" group="content" v-model:disabledbtn="disabledbtn" :limitNum="10" :limit="600" v-model:loading="loading" v-model:imageList="form.content" :imageNum="contentNum" suggestInfo="建议：图片大小1M以下" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { VueDraggableNext as draggable } from "vue-draggable-next";
import UploadImageInfo from "@/components/common/UploadImageInfo.vue";
import UploadImageListInfo from "@/components/common/UploadImageListInfo.vue";
import UploaVideoInfo from "@/components/common/UploaVideoInfo.vue";
import type { postOrPutType } from "@/constants";
import type { HasId, ViewMode } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import type { IDictData } from "@/types/dict";
import type { ISpecItem } from "@/types/redPacketMallManage/spec";
import type { IGoodsDetailVO, IGoodsDTO, IRentMobileOrderType, ISpec, PriceKey, SkuListName } from "@/types/rentMachineManage/phoneInfo";
import type { IGoodsCategory, ISearchGoodsCategory, ISearchStoreGoodsCategory, IStoreGoodsCategory } from "@/types/rentMachineManage/goodsCategory";
import { getGoodsCategoryList } from "@/utils/api/admin/goods/goodsCategory";
import { getStoreGoodsClassList } from "@/utils/api/admin/goods/storeGoodsClass";
import { commonGoodsInfo, getGoodsByIdInfo } from "@/utils/api/admin/goods/goods";
import { ElMessageBox, type FormRules } from "element-plus";
import { isNumber } from "@/shared";
const { disabledbtn, loading, toggleState } = useState();

interface Props {
  id: number;
  category1List: Array<IGoodsCategory>;
  platformList: Array<IDictData>;
  orderRentTypeList: Array<IRentMobileOrderType>;
  saleList: Array<IDictData>;
  selectWhether: Array<IDictData>;
  finenessList: Array<IDictData>;
  goodsTagList: Array<IDictData>;
  rankList: Array<IDictData>;
}
const { id, category1List, platformList, orderRentTypeList, saleList, selectWhether, finenessList, goodsTagList, rankList } = defineProps<Props>();

const formStatus = defineModel<ViewMode>("formStatus", { required: true });
const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
  getMallCategoryInfo: [];
  getMallDeliverInfo: [];
}>();

/* 商品分类2*/
const category2List = ref<Array<IGoodsCategory>>([]);
const storeCategory1List = ref<Array<IStoreGoodsCategory>>([]);
const storeCategory2List = ref<Array<IStoreGoodsCategory>>([]);

const isDisabledbtn = ref(false);
const imageNum = ref<number>(0);
const contentNum = ref<number>(0);
const formRef = useTemplateRef("formRef");
const uploadImageListRef = useTemplateRef("uploadImageListRef");
const uploadContentListRef = useTemplateRef("uploadContentListRef");
// const memoryInputRef = useTemplateRef("memoryInputRef");
// const colorInputRef = useTemplateRef("colorInputRef");
const methodType = ref<postOrPutType>("PUT");
const form = reactive<IGoodsDTO>({
  id: 0,
  goods_name: "",
  fineness: "",
  can_resale: "",
  cat_id1: "",
  cat_id2: "",
  cat_id3: "",
  store_cat_id1: "",
  store_cat_id2: "",
  store_id: "",
  shop_price: "",
  retail_price: "",
  market_price: "",
  month_price: "",
  next_year_month_price: "",
  buyout_price: "",
  advance_price: "",
  deposit_price: 0,
  min_price: "",
  max_price: 0,
  hot_sell_rank: "",
  is_diff_price: "",
  lease_price: 0,
  cost_price: 0,
  original_img: "",
  original_video: "",
  order_rent_type_ids: [],
  is_on_sale: "",
  store_count: 0,
  basic_sales_sum: 0,
  sort: 0,
  content: [],
  platform: [],
  goods_tags: [],
  image: [],
  sku: {
    color_list: [],
    memory_list: [],
    spec_list: []
  }
});

const specList = ref<Array<ISpecItem>>([]);

const specInfo = reactive({
  color: {
    inputVisible: false,
    inputValue: ""
  },
  memory: {
    inputVisible: false,
    inputValue: ""
  }
});

let advance = ref<number>(0);
const rules = reactive<FormRules<IGoodsDTO>>({
  goods_name: [{ required: true, message: "请填写手机型号", trigger: "blur" }],
  sort: [{ required: true, message: "请填写排序", trigger: "blur" }],
  original_img: [{ required: true, message: "请上传商品主图", trigger: "blur" }],
  cat_id1: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
  cat_id2: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
  store_cat_id1: [{ required: true, message: "请选择本店分类", trigger: "blur" }],
  store_cat_id2: [{ required: true, message: "请选择本店分类", trigger: "blur" }],
  platform: [{ required: true, message: "请选择下单平台", trigger: "blur" }],
  shop_price: [{ required: true, message: "请填写批发价", trigger: "blur" }],
  retail_price: [{ required: true, message: "请填写零售价", trigger: "blur" }],
  order_rent_type_ids: [{ required: true, message: "请选择模式", trigger: "blur" }],
  fineness: [{ required: true, message: "请选择商品成色", trigger: "blur" }],
  image: [{ required: true, message: "请上传商品轮播图", trigger: "blur" }],
  is_on_sale: [{ required: true, message: "请选择商品状态", trigger: "blur" }],
  month_price: [],
  next_year_month_price: [],
  buyout_price: [],
  advance_price: [],
  deposit_price: []
});

/* 某些平台下面才显示批发价 */
const showShopPrice = computed(() => {
  if ([7, 8, 10].includes(advance.value)) return true;
  return false;
});
/* 某些平台下面才显示零售价 */
const showRetailPrice = computed(() => {
  if ([0, 1, "", 9].includes(advance.value)) return true;
  return false;
});
/* 某些平台下面才显示官网价 */
// const showMarketPrice = computed(() => {
//   if ([17, 18, 19, 22].includes(advance.value)) return true;
//   return false;
// });
/* 某些平台下面才显示月供价 */
const showMonthPrice = computed(() => {
  const specificPlatforms = ["taobaoPlatform", "bytePlatform", "douyinPlatform", "kuaishouStorePlatform", "littleRedBookStorePlatform"];
  if ([9].includes(advance.value) || specificPlatforms.some(platform => form.platform.includes(platform))) return true;
  return false;
});
/* 某些平台下面才只显示月供价 */
const showAnyMonthPrice = computed(() => {
  if ([11].includes(advance.value)) return true;
  return false;
});
/* 某些平台下面才显示买断价和首付 */
const showBuyoutPriceAndAdvancePrice = computed(() => {
  if ([13, 14].includes(advance.value)) return true;
  return false;
});

/* 长租模式V5/长租模式V6显示买断价和押金 */
const showBuyoutPriceAndDepositPrice = computed(() => {
  if ([16].includes(advance.value)) return true;
  return false;
});

/* 显示最高价最低价 */
const showMaxMinPrice = computed(() => {
  if ([17, 18, 19, 22, 40, 43, 44, 45, 47, 48, 49].includes(advance.value)) return true;
  return false;
});

/* 显示线下租机模式 */
const showOfflineRental = computed(() => {
  if ([21].includes(advance.value)) return true;
  return false;
});

/* 显示新机信息 隐藏本地分类 */
const showLocalCategory = computed(() => {
  return form.cat_id1 == "639";
});
/* 线下二手机分类，选择的模式，显示成色，是否转卖 ，26, 27，29模式取消 */
const showOldMobiloeInfo = computed(() => {
  if ([24, 25, 26, 27, 30].includes(advance.value)) return true;
  return false;
});

/* 通过商品分类1显示不同的租赁模式 */
const optionalOrderRentTypeList = computed(() => {
  if ([639].includes(form.cat_id1 as number)) {
    return orderRentTypeList.filter(item => [24, 25, 26, 27, 30].includes(item.is_advance));
  } else if ([9].includes(form.cat_id1 as number)) {
    return orderRentTypeList.filter(item => [21].includes(item.is_advance));
  }
  return orderRentTypeList.filter(item => [13, 14, 19, 22, 40, 43, 44, 45, 47, 48, 49].includes(item.is_advance));
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});
/*  */
watch(
  () => id,
  newValue => {
    if (newValue == 0) {
      /* 初始化数据 */
    } else {
      form.id = newValue;
      handleGetAppUserByIdInfo(id);
    }
  }
);

/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  isDisabledbtn.value = false;

  form.id = 0;
  form.store_cat_id1 = "";
  form.store_cat_id2 = "";
  form.store_id = "";
  form.retail_price = "";
  form.shop_price = "";
  form.market_price = "";
  form.month_price = "";
  form.next_year_month_price = "";
  form.buyout_price = "";
  form.advance_price = "";
  form.deposit_price = "";
  form.min_price = "";
  form.max_price = "";
  form.hot_sell_rank = "";
  form.is_diff_price = "1";
  form.fineness = "";
  form.can_resale = "";

  advance.value = 0;
  imageNum.value = 0;
  contentNum.value = 0;
  uploadImageListRef.value?.handleClearImage();
  uploadContentListRef.value?.handleClearImage();
  specList.value = [];
  form.sku.color_list = [];
  form.sku.memory_list = [];
  form.sku.spec_list = [];
  form.image = [];
  form.content = [];
  form.order_rent_type_ids = [];
  category2List.value = [];
  storeCategory2List.value = [];
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
}

/* 通过id获取前端账户详情信息 */
function handleGetAppUserByIdInfo(id: number) {
  toggleState(true);
  getGoodsByIdInfo<IGoodsDetailVO, HasId>({ id })
    .then(res => {
      form.goods_name = res.result.goods_name;
      form.fineness = res.result.fineness;
      form.can_resale = res.result.can_resale + "";
      form.cat_id1 = res.result.cat_id1;
      form.cat_id2 = res.result.cat_id2;
      form.store_id = res.result.store.store_id;
      form.store_cat_id1 = res.result.store_cat_id1;
      form.store_cat_id2 = res.result.store_cat_id2;
      form.shop_price = res.result.shop_price;
      form.retail_price = res.result.retail_price;
      form.market_price = res.result.market_price;
      form.month_price = res.result.month_price;
      form.next_year_month_price = res.result.next_year_month_price;
      form.buyout_price = res.result.buyout_price;
      form.advance_price = res.result.advance_price;
      form.lease_price = res.result.lease_price;
      form.cost_price = res.result.cost_price;
      form.original_img = res.result.original_img;
      form.platform = res.result.platform;
      form.goods_tags = res.result.goods_tags;
      form.deposit_price = res.result.deposit_price;
      form.min_price = res.result.min_price;
      form.max_price = res.result.max_price;
      form.is_diff_price = res.result.is_diff_price;
      form.hot_sell_rank = res.result.hot_sell_rank ? res.result.hot_sell_rank + "" : "";
      if (res.result.original_video !== null && res.result.original_video !== "") {
        form.original_video = res.result.original_video;
      }

      form.order_rent_type_ids = res.result.order_rent_type_ids;

      form.is_on_sale = res.result.is_on_sale + "";
      form.store_count = res.result.store_count;
      form.basic_sales_sum = res.result.basic_sales_sum;
      form.sort = res.result.sort;

      handleChangePlatformRentType(form.order_rent_type_ids, true);

      if (res.result.sku !== null) {
        form.sku.memory_list = res.result.sku.memory_list;
        form.sku.color_list = res.result.sku.color_list;
        form.sku.spec_list = res.result.sku.spec_list;
      }

      form.image = res.result.image;
      imageNum.value = form.image.length;

      form.content = res.result.content;
      contentNum.value = res.result.content.length;

      /* 初始化规格数据 */
      handleReplenishSpecData();

      /* 需要根据模式和平台删除对应字段上的数据 */
      handleConditionalDeleteSpecToEmpty();
      /* 获取商品分类列表 */
      handleGetGoodsCategoryList(form.cat_id1, 2, category2List);
      // handleGetGoodsCategoryList(form.cat_id2, 3);
      /* 获取本店分类列表 */
      /* 不同店铺显示的本店分类不同，需要重新获取的 */
      handleGetStoreGoodsClassList(0, 1, form.store_id, storeCategory1List);
      handleGetStoreGoodsClassList(form.store_cat_id1, 2, form.store_id, storeCategory2List);
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}

/* 校验数据 */
function handleVerifyData() {
  return true;
}

/* 新增修改之前修改数据 */
function handleChangeData() {
  // if (form.stock_total === 0) {
  //   form.status = "outOfStock";
  // }
  // /* 格式化轮播图片 */
  // if (form.goods_images == "") {
  //   form.status = "hasBeenRemoved";
  // }
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    if (!handleVerifyData()) return;
    handleChangeData();
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  if (!handleVerifySku()) return;
  /* 防止多次提交 */
  toggleState(true);
  handleDelNullSpecData();
  handleInputEmptyForZero();
  commonGoodsInfo(form, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  // clearData();
  // activeName = "one";
  emit("handleInitData");
}

/* 填写空数据为0，防止后端报错 */
function handleInputEmptyForZero() {
  if (form.shop_price == "") form.shop_price = 0;
  if (form.retail_price == "") form.retail_price = 0;
  if (form.market_price == "") form.market_price = 0;
  if (form.month_price == "") form.month_price = 0;
  if (form.next_year_month_price == "") form.next_year_month_price = 0;
  if (form.buyout_price == "") form.buyout_price = 0;
  if (form.advance_price == "") form.advance_price = 0;
}
/* 删除空数据数据 */
function handleDelNullSpecData() {
  let i = form.sku.spec_list.length;
  while (i--) {
    if (form.sku.spec_list[i].month_price === "" && form.sku.spec_list[i].next_year_month_price === "" && form.sku.spec_list[i].price === "" && form.sku.spec_list[i].retail_price === "" && form.sku.spec_list[i].buyout_price === "" && form.sku.spec_list[i].advance_price === "") {
      form.sku.spec_list.splice(i, 1);
    }
  }
}

/* 校验sku价格 */
function handleVerifySkuPrice(price: PriceKey, priceName: string) {
  const length = form.sku.spec_list.length;
  for (let i = 0; i < length; i++) {
    const element = form.sku.spec_list[i][price];
    if (element == "") {
      ElMessage.warning(`请填写sku中的${priceName}`);
      return false;
    }
    if (!isNumber(element)) {
      ElMessage.warning(`请正确填写sku中的${priceName}`);
      return false;
    }
  }
  return true;
}

/* 校验sku数据是否必填 */
function handleVerifySku() {
  if (showRetailPrice.value) {
    /* "二折购机",校验零售价必填 */
    if (!handleVerifySkuPrice("retail_price", "零售价")) return false;
  } else if (showShopPrice.value) {
    /* 长租套餐, 校验批发价必填 */
    if (!handleVerifySkuPrice("price", "批发价")) return false;
  } else if (showAnyMonthPrice.value) {
    /* "12期租机",校验月供价必填 */
    if (!handleVerifySkuPrice("month_price", "首年月供价")) return false;
    if (!handleVerifySkuPrice("next_year_month_price", "下一年月供价")) return false;
  } else if (showBuyoutPriceAndAdvancePrice.value) {
    /* "6期通用",校验买断价和首付必填 */
    if (!handleVerifySkuPrice("buyout_price", "买断价")) return false;
    if (!handleVerifySkuPrice("advance_price", "首付")) return false;
  } else if (showBuyoutPriceAndDepositPrice.value) {
    /* "长租v5模式",校验买断价和押金和奖励必填 */
    if (!handleVerifySkuPrice("buyout_price", "买断价")) return false;
    if (!handleVerifySkuPrice("deposit_price", "押金")) return false;
    if (!handleVerifySkuPrice("subsidy_price", "奖励")) return false;
  } else if (showMaxMinPrice.value) {
    /* 四折，六折，全款购机模式必填零售价 */
    if (!handleVerifySkuPrice("retail_price", "零售价")) return false;
  }
  if (showOfflineRental.value) {
    /* 线下租机 */
    if (!handleVerifySkuPrice("price", "指导价")) return false;
    if (!handleVerifySkuPrice("retail_price", "最高限价")) return false;
    if (!handleVerifySkuPrice("regulatory_recycling_price", "监管机回收价")) return false;
  }
  return true;
}

/* 商品分类的change事件 */
function handleChangeCategory(parent_id: number, level: number) {
  if (level === 2) {
    category2List.value = [];
    form.cat_id2 = "";
    /* 删除租赁模式 */
    form.order_rent_type_ids = [];
  }
  handleGetGoodsCategoryList(parent_id, level, category2List);
}

/* 获取商品分类 */
function handleGetGoodsCategoryList(parent_id: number, level: number, categoryList: Ref<IGoodsCategory[]>) {
  getGoodsCategoryList<IGoodsCategory[], ISearchGoodsCategory>({
    parent_id,
    level
  })
    .then(res => {
      categoryList.value = res.result;
    })
    .catch(() => {});
}

/* 本地商品分类的change事件 */
function handleChangeStoreCategory(parent_id: number) {
  storeCategory2List.value = [];
  form.store_cat_id2 = "";
  handleGetStoreGoodsClassList(parent_id, 2, form.store_id, storeCategory2List);
}

/* 获取商品分类 */
function handleGetStoreGoodsClassList(parent_id: number, level: number, store_id: number | string, storeCategoryList: Ref<IStoreGoodsCategory[]>) {
  getStoreGoodsClassList<IStoreGoodsCategory[], ISearchStoreGoodsCategory>({
    parent_id,
    store_id
  })
    .then(res => {
      if (level === 1) {
        if (["", "11378", 11378].includes(store_id)) {
          let result = res.result.filter(item => {
            return [553, 286].includes(item.id);
          });
          storeCategoryList.value = result;
        } else {
          storeCategoryList.value = res.result;
        }
      } else {
        storeCategoryList.value = res.result;
      }
    })
    .catch(() => {});
}

/* 选择租赁模式 */
function handleChangePlatformRentType(ids: number[], init: boolean = false) {
  if (ids.length > 1) {
    if (!isSameRentMode(ids[0], ids[ids.length - 1])) {
      ElMessage.error("此租赁模式不能与之前选中的模式同时存在");
      return;
    }
  }
  if (!init) {
    if (form.sku.color_list.length == 0) {
      form.sku.spec_list = [];
    }
  }
  form.order_rent_type_ids = ids;
  advance.value = 0;
  rules.shop_price = [{ required: true, message: "请填写批发价", trigger: "blur" }];
  rules.retail_price = [{ required: true, message: "请填写零售价", trigger: "blur" }];
  rules.image = [{ required: true, message: "请上传轮播图", trigger: "blur" }];
  nextTick(() => {
    formRef.value?.clearValidate();
  });

  const id = ids[ids.length - 1];
  const i = orderRentTypeList.findIndex(item => item.id == id);
  if (i === -1) return;
  advance.value = orderRentTypeList[i].is_advance;
  console.log(advance.value);

  if (showRetailPrice.value) {
    /* "二折购机",显示零售价 */
    rules.shop_price = [];
  } else if (showShopPrice.value) {
    /* 长租套餐,显示批发价 */
    rules.retail_price = [];
  } else if (showAnyMonthPrice.value) {
    rules.retail_price = [];
    rules.shop_price = [];
    rules.month_price = [{ required: true, message: "请填写月供价", trigger: "blur" }];
    rules.next_year_month_price = [{ required: true, message: "请填写下一年月供价", trigger: "blur" }];
  } else if (showBuyoutPriceAndAdvancePrice.value) {
    rules.retail_price = [];
    rules.shop_price = [];
    rules.buyout_price = [{ required: true, message: "请填写买断价", trigger: "blur" }];
    rules.advance_price = [{ required: true, message: "请填写首付价", trigger: "blur" }];
  } else if (showBuyoutPriceAndDepositPrice.value) {
    rules.retail_price = [];
    rules.shop_price = [];
    rules.buyout_price = [{ required: true, message: "请填写买断价", trigger: "blur" }];
    rules.deposit_price = [{ required: true, message: "请填写押金", trigger: "blur" }];
  } else if (showMaxMinPrice.value) {
    rules.retail_price = [];
    rules.shop_price = [];
  } else if (showOfflineRental.value) {
    rules.retail_price = [];
    rules.is_diff_price = [{ required: true, message: "请选择是否补差价", trigger: "blur" }];
    rules.image = [];
    if (!init) {
      /* 删除颜色列表 */
      form.sku.spec_list = [];
      form.sku.color_list = [];
      const memoryList = form.sku["memory_list"];
      for (let i = 0; i < memoryList.length; i++) {
        handlePushSpecList("", memoryList[i].item);
      }
    }
  } else if (showOldMobiloeInfo.value) {
    rules.retail_price = [];
    rules.shop_price = [];
    rules.can_resale = [{ required: true, message: "请选择是否转卖", trigger: "blur" }];
  }
  nextTick(() => {
    formRef.value?.clearValidate();
  });
}
/* 是否相同的租机模式 */
function isSameRentMode(id1: number, id2: number) {
  const data = orderRentTypeList.find(item => item.id == id2);
  /* 这样写的原因：模式删除了，但是线上商品数据中还有模式，列表中模式删除了，可能存在找不到的情况 */
  if (!data) return true;
  /* 只需要判断 */
  const _data = orderRentTypeList.find(item => item.id == id1);
  if (!_data) return true;
  return _data.mode == data.mode;
}
/* 补充规格列表数据（有些没填的数据，没传给后端，编辑的时候，导致数据会不全） */
function handleReplenishSpecData() {
  for (let i = 0; i < form.sku.color_list.length; i++) {
    const color = form.sku.color_list[i].item;
    for (let j = 0; j < form.sku.memory_list.length; j++) {
      const memory = form.sku.memory_list[j].item;
      let isExist = false;
      const spec_list = form.sku.spec_list;
      for (let k = 0; k < spec_list.length; k++) {
        const mobile_sku = spec_list[k];
        if (mobile_sku.color === color && mobile_sku.memory === memory) {
          isExist = true;
          break;
        }
      }
      if (!isExist) {
        handlePushSpecList(color, memory);
      } else {
        form.sku.spec_list = handleSpecSort();
      }
    }
  }
}

/* 需要根据模式和平台删除对应字段上的数据 */
function handleConditionalDeleteSpecToEmpty() {
  for (let i = 0; i < form.sku.spec_list.length; i++) {
    const element = form.sku.spec_list[i];
    if (!Number(element.price)) {
      element.price = "";
    }
    if (!Number(element.retail_price)) {
      element.retail_price = "";
    }
    if (!Number(element.month_price)) {
      element.month_price = "";
    }
    if (!Number(element.next_year_month_price)) {
      element.next_year_month_price = "";
    }
  }
}

/* 拖拽修改规格数据后，重新排序sku数据  */
function handleChangDraggable() {
  form.sku.spec_list = handleSpecSort();
}
/* 删除某个 规格值 */
function handleDeleteColorValue(item: string, name: "memory" | "color", list: SkuListName) {
  ElMessageBox.confirm("规格名删除后无法取消，确认删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      /* 删除规格组中对应的规格值信息 */
      for (let i = 0; i < form.sku[list].length; i++) {
        if (form.sku[list][i].item === item) {
          form.sku[list].splice(i, 1);
          break;
        }
      }
      ElMessage.success("删除成功!");
      /* 删除规格列表中的数据 */
      let i = form.sku.spec_list.length;
      while (i--) {
        if (form.sku.spec_list[i][name] === item) {
          form.sku.spec_list.splice(i, 1);
        }
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
}

/* 新增规格值 */
function handleInputConfirm(name: "memory" | "color", list: SkuListName) {
  specInfo[name].inputVisible = false;
  if (specInfo[name].inputValue === "") return;
  const temp = specInfo[name].inputValue;
  for (let i = 0; i < form.sku[list].length; i++) {
    if (form.sku[list][i].item === temp) {
      ElMessage.warning("规格值不能重复，请重新添加");
      return;
    }
  }
  form.sku[list].push({
    id: -Date.now(),
    item: temp
  });
  specInfo[name].inputValue = "";
  handleChangeSpecList(temp, list);
}
/* 修改规格列表信息 */
function handleChangeSpecList(value: string, list: SkuListName) {
  if (form.sku[list].length === 0) return;
  if (showOfflineRental.value) {
    /* 单规格的情况 */
    for (let i = 0; i < form.sku[list].length; i++) {
      handlePushSpecList(value, form.sku[list][i].item);
    }
  } else {
    /* 多规格的情况 */
    /* 修改规格列表信息 */
    list = list === "color_list" ? "memory_list" : "color_list";
    for (let i = 0; i < form.sku[list].length; i++) {
      if (list === "memory_list") {
        handlePushSpecList(value, form.sku[list][i].item);
      } else if (list === "color_list") {
        handlePushSpecList(form.sku[list][i].item, value);
      }
    }
  }
}

/* push规格数据 */
function handlePushSpecList(color: string, memory: string) {
  let info: ISpec = {
    key: Symbol(),
    color,
    memory,
    price: "",
    sku: "",
    retail_price: "",
    lease_price: 0,
    month_price: "",
    deposit_price: "",
    subsidy_price: "",
    buyout_price: "",
    official_price: "",
    next_year_month_price: "",
    advance_price: "",
    store_count: 9999,
    image: "",
    goods_id: 0,
    key_name: "",
    bar_code: "",
    store_id: "",
    regulatory_recycling_price: ""
  };
  form.sku.spec_list.push(info);
  form.sku.spec_list = handleSpecSort();
  handleChangeStoreCount();
}
/* 规格排序 */
function handleSpecSort() {
  let specList = [],
    l = form.sku.memory_list.length;
  if (!showOfflineRental.value) {
    /* 多规格排序 */
    for (let j = 0; j < l; j++) {
      const memory = form.sku.memory_list[j].item;
      for (let i = 0; i < form.sku.color_list.length; i++) {
        const color = form.sku.color_list[i].item;
        const spec_list = form.sku.spec_list;
        for (let k = 0; k < spec_list.length; k++) {
          const mobile_sku = spec_list[k];
          if (mobile_sku.memory === memory && mobile_sku.color === color) {
            specList.push(mobile_sku);
            break;
          }
        }
      }
    }
  } else {
    /* 单规格排序 */
    for (let j = 0; j < l; j++) {
      const memory = form.sku.memory_list[j].item;
      const spec_list = form.sku.spec_list;
      for (let k = 0; k < spec_list.length; k++) {
        const mobile_sku = spec_list[k];
        if (mobile_sku.memory === memory) {
          specList.push(mobile_sku);
          break;
        }
      }
    }
  }
  return specList;
}
/* 修改库存的change事件 */
function handleChangeStoreCount() {
  form.store_count = form.sku.spec_list.map(item => item.store_count).reduce((prev, cur) => +prev + +cur);
}
/* 点击新增tag标签 */
function showInput(name: "memory" | "color") {
  specInfo[name].inputVisible = true;
  // nextTick(() => {
  //   refs?.value?.focus();
  // });
}
/* 批量修改sku中的价格信息（不存在的价格才修改） */
function handleChangeSkuPrice(value: string, { key, memory }: ISpec, priceKey: PriceKey) {
  for (let i = 0; i < form.sku.spec_list.length; i++) {
    const item = form.sku.spec_list[i];
    if (item.key !== key && item.memory == memory && item[priceKey] == "") {
      item[priceKey] = value;
    }
  }
}

handleGetStoreGoodsClassList(0, 1, "", storeCategory1List);
</script>

<style lang="scss" scoped>
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}

/* tag相关 start */
.tags-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-right: 10px;
}
.input-new-tag {
  width: 140px;
}
/* end */
</style>
